package com.zzwx.controller.shiro;

import com.zzwx.dao.entity.sys.Role;
import com.zzwx.dao.entity.sys.User;
import com.zzwx.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 权限验证
     * @param principalCollection PrincipalCollection
     * @return AuthorizationInfo
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        String name = (String)principalCollection.getPrimaryPrincipal();
        Role role = userService.findRoleByName(name);
        info.addRole(role.getRoleName());

        Set<String> menus = userService.findMenuByRoleId(role.getId());
        info.addStringPermissions(menus);

        return info;
    }

    /**
     * 登陆验证
     * @param token AuthenticationToken
     * @return AuthenticationInfo
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = String.valueOf(token.getPrincipal()); // 用户名
        User user = userService.findUserByName(userName);

        if(null == user){
            throw new UnknownAccountException("当前账户没有找到");
        }

        if(!user.getPassword().equals(new String((char[]) token.getCredentials()))){
            throw new IncorrectCredentialsException("密码不匹配");
        }

        if(user.getStatus() == 0){
            throw new LockedAccountException("该账户已被锁定");
        }

        return new SimpleAuthenticationInfo(userName,user.getPassword(),getName());
    }
}
